import { createSlice, type PayloadAction } from '@reduxjs/toolkit';
import type { UserInfo, UserState } from '../types';

// 初始状态
const initialState: UserState = {
  isLoggedIn: false,
  userInfo: null,
  loading: false,
  error: null,
};

// 创建slice
const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    // 设置加载状态
    setLoading: (state, action: PayloadAction<boolean>) => {
      state.loading = action.payload;
    },

    // 设置错误信息
    setError: (state, action: PayloadAction<string | null>) => {
      state.error = action.payload;
    },

    // 登录成功
    loginSuccess: (state, action: PayloadAction<UserInfo>) => {
      state.isLoggedIn = true;
      state.userInfo = action.payload;
      state.loading = false;
      state.error = null;
    },

    // 登录失败
    loginFailure: (state, action: PayloadAction<string>) => {
      state.isLoggedIn = false;
      state.userInfo = null;
      state.loading = false;
      state.error = action.payload;
    },

    // 登出
    logout: (state) => {
      state.isLoggedIn = false;
      state.userInfo = null;
      state.loading = false;
      state.error = null;
    },

    // 更新用户信息
    updateUserInfo: (state, action: PayloadAction<Partial<UserInfo>>) => {
      if (state.userInfo) {
        state.userInfo = { ...state.userInfo, ...action.payload };
      }
    },

    // 清除错误
    clearError: (state) => {
      state.error = null;
    },
  },
});

// 导出actions
export const {
  setLoading,
  setError,
  loginSuccess,
  loginFailure,
  logout,
  updateUserInfo,
  clearError,
} = userSlice.actions;

// 导出reducer
export default userSlice.reducer;